package com.eksframework.commons.core.validator;

import javax.validation.ConstraintViolation;
import java.util.Set;

/**
 * 校验结果
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-12-03 10:32
 */
public class ValidatorResult<T> {

    /**
     * 校验结果错误集
     */
    private final Set<ConstraintViolation<T>> violationErrorSet;

    /**
     * Constructor.
     */
    public ValidatorResult(Set<ConstraintViolation<T>> violations) {
        this.violationErrorSet = violations;
    }

    /**
     * 是否有校验错误
     *
     * @return boolean
     */
    public boolean hasError() {
        return this.violationErrorSet != null && !this.violationErrorSet.isEmpty();
    }

    /**
     * 获取校验错误数量
     *
     * @return int
     */
    public int getErrorCount() {
        if (!hasError()) {
            return 0;
        }
        return violationErrorSet.size();
    }

    /**
     * 获取校验错误结果集
     *
     * @return Set of ConstraintViolation
     */
    public Set<ConstraintViolation<T>> getErrorSet() {
        return this.violationErrorSet;
    }

    /**
     * 获取一个校验错误结果
     *
     * @return ConstraintViolation
     */
    public ConstraintViolation<T> getOneError() {
        if (!hasError()) {
            return null;
        }
        return this.violationErrorSet.iterator().next();
    }

    /**
     * 如果存在校验错误，则抛出异常
     */
    public void throwIf() {
        if (hasError()) {
            throw new IllegalArgumentException(getMessageDetail());
        }
    }

    /**
     * 获取一个错误信息
     *
     * @return String
     */
    public String getOneMessage() {
        if (!hasError()) {
            return null;
        }
        ConstraintViolation<?> violation = getOneError();
        return "[" +
                violation.getPropertyPath() +
                "]" +
                violation.getMessage();
    }

    /**
     * 获取所有错误信息
     *
     * @return String
     */
    public String getAllMessage() {
        if (!hasError()) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        violationErrorSet.forEach(violation -> {
            if (result.length() > 0) {
                result.append("; ");
            }
            result.append("[")
                    .append(violation.getPropertyPath()).append("]")
                    .append(violation.getMessage());
        });
        return result.toString();
    }

    /**
     * 获取错误信息明细
     *
     * @return String
     */
    public String getMessageDetail() {
        if (!hasError()) {
            return null;
        }
        int errorCount = getErrorCount();
        StringBuilder result = new StringBuilder();
        result.append("Validation failed ");
        if (errorCount > 1) {
            result.append("with ").append(errorCount).append(" errors");
        }
        result.append(": ");
        result.append(getAllMessage());
        return result.toString();
    }
}
